<template>
    <div v-if="weatherData.adCode.city && weatherData.weather.weather" class="weather">
        <span>{{ weatherData.adCode.city }}&nbsp;</span>
        <span>{{ weatherData.weather.weather }}&nbsp;</span>
        <span>{{ weatherData.weather.temperature }}℃</span>
        <span class="sm-hidden">
      &nbsp;{{
            weatherData.weather.winddirection?.endsWith("风")
                ? weatherData.weather.winddirection
                : weatherData.weather.winddirection + "风"
            }}&nbsp;
    </span>
        <span class="sm-hidden">{{ weatherData.weather.windpower }}&nbsp;级</span>
    </div>
    <div v-else class="weather">
        <span>天气数据获取失败</span>
    </div>
</template>

<script setup>
import {getOtherWeather} from "@/api";
import {Error} from "@icon-park/vue-next";
import {h, onMounted, reactive} from "vue";

// 天气数据
const weatherData = reactive({
    adCode: {
        city: null, // 城市
        adcode: null, // 城市编码
    },
    weather: {
        weather: null, // 天气现象
        temperature: null, // 实时气温
        winddirection: null, // 风向描述
        windpower: null, // 风力级别
    },
});

// 获取天气数据
const getWeatherData = () => {
    // 获取地理位置信息
    getOtherWeather()
        .then((res) => {
            const data = res.result;
            weatherData.adCode = {
                city: data.city.city_name,
                adcode: data.city.cityId,
            };
            weatherData.weather = {
                weather: data.condition.condition,
                temperature: data.condition.temp,
                winddirection: data.condition.windDir,
                windpower: data.condition.windLevel,
            };
        })
        .catch((err) => {
            console.error("天气信息获取失败:" + err);
            onError("天气信息获取失败");
        });
};

// 报错信息
const onError = (message) => {
    ElMessage({
        message,
        icon: h(Error, {
            theme: "filled",
            fill: "#efefef",
        }),
    });
    console.error(message);
};

onMounted(() => {
    // 调用获取天气
    getWeatherData();
});
</script>
